from pydantic import BaseModel,ValidationError,field_validator,Field

# class User(BaseModel):
#     email: str
#     @field_validator('email')
#     def validate_email(cls, vv):
#         if"@" not in vv:
#             raise ValidationError("Invalid email address")
#         return vv.lower()

#正确
# user = User(email="349074390@qq.com") #自动转换为小写:applice@example.com
# print(user)

#错误
# User(email="invalid") #触发 ValueError


# class User(BaseModel):
#     username: str = Field(...,min_length=3)
#
#     @field_validator('username')
#     def validate_username(cls,value):
#         if "admin" in value:
#             raise ValidationError("<UNK>")
#         return value
# #正确
# User(username="xxx123")

#错误
# User(username="admin") #触发自定义验证错误


# class Account(BaseModel):
#     password: str
#
#     @field_validator('password')
#     def check_password(cls, value):
#         errors = []
#         if len(value) < 8:
#             errors.append("Password must be at least 8 characters")
#         if not any(c.isupper() for c in  value): #至少包含一个大写
#             errors.append("Password must contain at least one uppercase character")
#         if errors:
#             raise ValueError(";".join(errors))
#         return value
#
# #错误
# Account(password="33333333333")


class Product(BaseModel):
    price: float
    cost: float

    @field_validator("price", "cost")
    def check_positive(cls, v):
        if v <= 0:
            raise ValueError("必须大于0")
        return v

# 同时验证price和cost是否为正数
Product(price=1, cost=-2)